package cn.conac.rc.gateway.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.GenericFilterBean;

import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.gateway.security.JwtTokenUtil;
import cn.conac.rc.gateway.security.vo.JwtUser;

public class JwtAuthenticationTokenFilter extends GenericFilterBean {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        //ie9上传时headers中加入不了token因此在url中增加udkey传输token信息
        //如果遇到其他插件访问时遇到此情况也可这样使用
        String token = httpRequest.getParameter("udkey");

        String authToken = httpRequest.getHeader(this.tokenHeader);
        if(StringUtils.isBlank(authToken)){
            authToken = token;
        }
        String username = jwtTokenUtil.getUsernameFromToken(authToken);

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            if(!jwtTokenUtil.isTokenExpired(authToken)){
                //TODO 过一段时间与DB进行用户有效性校验
                JwtUser userDetails = jwtTokenUtil.getUserFromToken(authToken);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            
        }

        chain.doFilter(request, response);
    }
}